package com.example.onlineanswer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlineanswer.common.annotation.RequiresLogin;
import com.example.onlineanswer.common.api.CommonResult;
import com.example.onlineanswer.model.entity.Answer;
import com.example.onlineanswer.model.vo.AnswerStatisticsVO;
import com.example.onlineanswer.model.vo.UserAnswerVO;
import com.example.onlineanswer.service.AnswerService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 答题管理控制器
 */
@RestController
@RequestMapping("/api/answer")
@RequiredArgsConstructor
public class AnswerController {

    private final AnswerService answerService;

    /**
     * 提交答案
     *
     * @param answer 答题信息
     * @return 是否成功
     */
    @PostMapping("/submit")
    @RequiresLogin
    public CommonResult<Boolean> submitAnswer(@RequestBody Answer answer) {
        boolean success = answerService.submitAnswer(answer);
        return success ? CommonResult.success(true) : CommonResult.failed("提交失败，请勿重复提交");
    }

    /**
     * 获取用户在某场竞赛中的答题记录
     *
     * @param userId    用户ID
     * @param contestId 竞赛ID
     * @return 答题记录列表
     */
    @GetMapping("/user/{userId}/contest/{contestId}")
    public CommonResult<List<UserAnswerVO>> getUserAnswers(
            @PathVariable Long userId,
            @PathVariable Long contestId) {
        List<UserAnswerVO> answers = answerService.getUserAnswersByContestId(userId, contestId);
        return CommonResult.success(answers);
    }

    /**
     * 查询指定竞赛的所有答题记录（分页）
     *
     * @param current    当前页
     * @param size       每页大小
     * @param contestId  竞赛ID
     * @param questionId 题目ID（可选）
     * @param userId     用户ID（可选）
     * @param isCorrect  是否正确（可选）
     * @return 答题记录列表
     */
    @GetMapping("/contest/{contestId}")
    public CommonResult<IPage<UserAnswerVO>> getContestAnswers(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @PathVariable Long contestId,
            @RequestParam(required = false) Long questionId,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Boolean isCorrect) {
        Page<UserAnswerVO> page = new Page<>(current, size);
        IPage<UserAnswerVO> result = answerService.pageContestAnswers(page, contestId, questionId, userId, isCorrect);
        return CommonResult.success(result);
    }

    /**
     * 获取题目的答题统计
     *
     * @param contestId  竞赛ID
     * @param questionId 题目ID
     * @return 答题统计
     */
    @GetMapping("/statistics/contest/{contestId}/question/{questionId}")
    public CommonResult<AnswerStatisticsVO> getQuestionAnswerStatistics(
            @PathVariable Long contestId,
            @PathVariable Long questionId) {
        AnswerStatisticsVO statistics = answerService.getQuestionAnswerStatistics(contestId, questionId);
        return CommonResult.success(statistics);
    }

    /**
     * 检查用户是否已回答过指定题目
     *
     * @param userId     用户ID
     * @param contestId  竞赛ID
     * @param questionId 题目ID
     * @return 是否已回答
     */
    @GetMapping("/check")
    public CommonResult<Boolean> hasUserAnswered(
            @RequestParam Long userId,
            @RequestParam Long contestId,
            @RequestParam Long questionId) {
        boolean hasAnswered = answerService.hasUserAnswered(userId, contestId, questionId);
        return CommonResult.success(hasAnswered);
    }

    /**
     * 更新答题状态
     *
     * @param id     答题ID
     * @param status 状态
     * @return 是否成功
     */
    @PutMapping("/{id}/status")
    @RequiresLogin
    public CommonResult<Boolean> updateAnswerStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        boolean success = answerService.updateAnswerStatus(id, status);
        return success ? CommonResult.success(true) : CommonResult.failed("更新失败");
    }

    /**
     * 计算竞赛的答题统计
     *
     * @param contestId 竞赛ID
     * @return 是否成功
     */
    @PostMapping("/calculate-statistics/{contestId}")
    @RequiresLogin
    public CommonResult<Boolean> calculateContestStatistics(@PathVariable Long contestId) {
        boolean success = answerService.calculateContestStatistics(contestId);
        return success ? CommonResult.success(true) : CommonResult.failed("计算失败");
    }
} 